package com.lst.projectlib.component.datetimepicker;

import java.util.ArrayList;
import java.util.List;

import com.lst.projectlib.R;
import com.lst.projectlib.util.DensityUtil;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TextView;
import android.widget.TimePicker;

public class DateTimePickerActivity extends Activity implements OnClickListener, OnDateChangedListener {

	public static final String INTENT_BUNDLE_KEY_INITIAL_YEAR = "initial_year";
	public static final String INTENT_BUNDLE_KEY_INITIAL_MONTH = "initial_month";
	public static final String INTENT_BUNDLE_KEY_INITIAL_DAY = "initial_day";
	public static final String INTENT_BUNDLE_KEY_SELECT_SINGLE_DATE = "select_single_date";
	
	public static final String INTENT_BUNDLE_KEY_INITIAL_HOUR = "initial_hour";
	public static final String INTENT_BUNDLE_KEY_INITIAL_MINUTE = "initial_minute";
	public static final String INTENT_BUNDLE_KEY_INITIAL_TITLE = "initial_title";
	public static final String INTENT_BUNDLE_KEY_SELECT_SINGLE_TIME = "select_single_time";

	private DatePicker mDatePicker;
	private TimePicker mTimePicker;

	private int request_code = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_date_time_picker);

		TextView tv_ok = (TextView) this.findViewById(R.id.tv_ok);
		TextView tv_cancel = (TextView) this.findViewById(R.id.tv_cancel);
		tv_ok.setOnClickListener(this);
		tv_cancel.setOnClickListener(this);

		mDatePicker = (DatePicker) this.findViewById(R.id.date_picker);
		
		mTimePicker = (TimePicker) this.findViewById(R.id.time_picker);

		// initialize state
		mTimePicker.setIs24HourView(true);
		
		resizePikcer(mDatePicker);

		initData();
	}

	private void initData() {
		Intent intent = getIntent();

		if (intent != null) {
			int year = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_YEAR, 0);
			int month = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_MONTH, 0);
			int day = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_DAY, 0);

			// 系统拿到的月份会小1（应该是从0计算的，所以得自己做处理，减去1）
			month--;

			mDatePicker.init(year, month, day, this);
			
			int hourOfDay = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_HOUR, 0);
			int minute = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_MINUTE, 0);
			mTimePicker.setCurrentHour(hourOfDay);
			mTimePicker.setCurrentMinute(minute);

			request_code = intent.getIntExtra("request_code", 0);
		}
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.tv_cancel) {
			finish();
		} else if (v.getId() == R.id.tv_ok) {
			tryNotifyTimeSet();
			finish();
		}
	}

	private void tryNotifyTimeSet() {
		if (mDatePicker != null && mTimePicker != null) {
			mDatePicker.clearFocus();
			mTimePicker.clearFocus();

			Intent intent = new Intent();
			intent.putExtra("request_code", request_code);

			String year = String.valueOf(mDatePicker.getYear());

			// 系统拿到的月份会小1（应该是从0计算的，所以得自己做处理，加上1）
			int nMonth = mDatePicker.getMonth() + 1;
			String month = nMonth < 10 ? ("0" + nMonth) : String.valueOf(nMonth);

			String day = mDatePicker.getDayOfMonth() < 10 ? ("0" + mDatePicker.getDayOfMonth())
					: String.valueOf(mDatePicker.getDayOfMonth());
			
			String hour = mTimePicker.getCurrentHour() < 10 ? ("0" + mTimePicker.getCurrentHour()) : String.valueOf(mTimePicker.getCurrentHour());
			String minute = mTimePicker.getCurrentMinute() < 10 ? ("0" + mTimePicker.getCurrentMinute()) : String.valueOf(mTimePicker.getCurrentMinute());
			
			intent.putExtra(INTENT_BUNDLE_KEY_SELECT_SINGLE_DATE, year + "/" + month + "/" + day);
			intent.putExtra(INTENT_BUNDLE_KEY_SELECT_SINGLE_TIME, hour + ":" + minute);
			this.setResult(RESULT_OK, intent);
		}
	}

	@Override
	public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

	}
	
	/**
	 * 调整FrameLayout大小
	 * @param tp
	 */
	private void resizePikcer(FrameLayout tp) {
		try {
			List<NumberPicker> npList = findNumberPicker(tp);
			for (NumberPicker np : npList) {
				resizeNumberPicker(np);
			}
		} catch (Exception e) {
		}
	}
	
	/**
	 * 得到viewGroup里面的numberpicker组件
	 * @param viewGroup
	 * @return
	 */
	private List<NumberPicker> findNumberPicker(ViewGroup viewGroup){
		List<NumberPicker> npList = new ArrayList<NumberPicker>();
		View child = null;
		if(null != viewGroup){
			for(int i = 0; i < viewGroup.getChildCount(); i++){
				child = viewGroup.getChildAt(i);
				if(child instanceof NumberPicker){
					npList.add((NumberPicker)child);
				}
				else if(child instanceof LinearLayout){
					List<NumberPicker> result = findNumberPicker((ViewGroup)child);
					if(result.size()>0){
						return result;
					}
				}
			}
		}
		return npList;
	}
	
	/*
	 * 调整numberpicker大小
	 */
	private void resizeNumberPicker(NumberPicker np){
		if (np != null) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px(this, 50), LinearLayout.LayoutParams.WRAP_CONTENT);
			params.setMargins(DensityUtil.dip2px(this, 5), 0, DensityUtil.dip2px(this, 5), 0);
			np.setLayoutParams(params);
		}
	}
}
